package de.hwr.chronix.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.core.El;
import com.extjs.gxt.ui.client.core.XDOM;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.DateWrapper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ComponentPlugin;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.RowEditor;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.hwr.chronix.client.dto.PollDTO;
import de.hwr.chronix.client.dto.TimeslotAdminDTO;
import de.hwr.chronix.shared.validator.DauerValidator;
import de.hwr.chronix.shared.validator.EMailValidator;

public class Formular_Abstimmung extends LayoutContainer {
	private FormData					formData;
	private VerticalPanel				vp;
	private FormPanel					simple;
	private TextField<String>			titel;
	private TextField<String>			ort;
	private TextField<String>			dauer;
	private TextArea					beschreibung;
	private TextField<String>			owner;
	private TextField<String>			email;
	private PollDTO						poll;
	

	public final ChronixServiceAsync	chronixService	= GWT.create(ChronixService.class);

	@Override
	protected void onRender(Element parent, int index) {

		super.onRender(parent, index);
		formData = new FormData("-20");
		vp = new VerticalPanel();
		vp.setSpacing(10);
		createForm1();
		add(vp);
	}

	private void createForm1() {
		simple = new FormPanel();
		// final FormPanel simple = new FormPanel();
		simple.setHeading("Abstimmung erstellen");
		simple.setFrame(true);
		simple.setWidth(350);

		ComponentPlugin plugin = new ComponentPlugin() {
			public void init(Component component) {
				component.addListener(Events.Render, new Listener<ComponentEvent>() {
					public void handleEvent(ComponentEvent be) {
						El elem = be.getComponent().el().findParent(".x-form-element", 3);
						// should style in external CSS rather than directly
						elem.appendChild(XDOM
								.create("<div style='color: #615f5f;padding: 1 0 2 0px;'>"
										+ be.getComponent().getData("text") + "</div>"));
					}
				});
			}
		};

		titel = new TextField<String>();
		titel.setFieldLabel("Title");
		titel.setAllowBlank(false);
		titel.addPlugin(plugin);
		titel.setData("text", "(Pflicht)");
		simple.add(titel, formData);

		ort = new TextField<String>();
		ort.setFieldLabel("Ort");
		ort.setAllowBlank(true);
		simple.add(ort, formData);

		dauer = new TextField<String>();
		dauer.setFieldLabel("Dauer");
		dauer.setAllowBlank(false);
		dauer.addPlugin(plugin);
		dauer.setValidator(new DauerValidator());
		dauer.setData("text", "(Pflicht) Angabe in Stunden");
		simple.add(dauer, formData);

		beschreibung = new TextArea();
		beschreibung.setPreventScrollbars(true);
		beschreibung.setFieldLabel("Beschreibung");
		simple.add(beschreibung, formData);

		owner = new TextField<String>();
		owner.setFieldLabel("Name");
		owner.setAllowBlank(false);
		owner.addPlugin(plugin);
		owner.setData("text", "(Pflicht)");
		simple.add(owner, formData);

		email = new TextField<String>();
		email.setFieldLabel("Email");
		email.setAllowBlank(false);
		email.addPlugin(plugin);
		email.setValidator(new EMailValidator());
		email.setData("text", "(Pflicht)");
		simple.add(email, formData);

		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		ColumnConfig column = new ColumnConfig();

		DateField dateField = new DateField();
		dateField.getPropertyEditor().setFormat(DateTimeFormat.getFormat("dd.MM.y"));
		column.setId("datum");
		column.setHeader("Datum");
		column.setWidth(95);

		column.setWidth(95);
		column.setEditor(new CellEditor(dateField));
		column.setDateTimeFormat(DateTimeFormat.getFormat("dd.MM.yyyy"));
		configs.add(column);

		column = new ColumnConfig();

		final TimeField timeField = new TimeField() {
			{
				setFormat(DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT));
				setIncrement(30);
			}
		};

		column.setId("startzeit");
		column.setHeader("startzeit");
		column.setSortable(false);
		// column.setDataIndex("datum");

		column.setDateTimeFormat(DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT));
		column.setEditor(new CellEditor(timeField) {
			public Object preProcessValue(Object value) {
				if (value == null) {
					return value;
				}
				Date d = (Date) value;

				return timeField.findModel(d);
			}

			@Override
			public Object postProcessValue(Object value) {
				DateTimeFormat df = DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT);
				if (value == null) {
					return df.parse("00:00");
				}
				ModelData bmd = ((ModelData) value);
				String time = bmd.get("text");
				return df.parse(time);
			}

		});

		column.setWidth(95);

		configs.add(column);
		column = new ColumnConfig();
		// endzeit
		final TimeField endzeit = new TimeField() {
			{
				setFormat(DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT));
				setIncrement(30);

			}
		};

		column.setId("endzeit");
		column.setHeader("Endzeit");
		column.setSortable(false);

		column.setDateTimeFormat(DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT));
		column.setEditor(new CellEditor(endzeit) {

			public Object preProcessValue(Object value) {
				if (value == null) {
					return value;
				}
				Date d = (Date) value;

				return endzeit.findModel(d);
			}

			@Override
			public Object postProcessValue(Object value) {
				DateTimeFormat df = DateTimeFormat.getFormat(PredefinedFormat.TIME_SHORT);
				if (value == null) {
					return df.parse("00:00");
				}
				ModelData bmd = ((ModelData) value);
				String time = bmd.get("text");
				return df.parse(time);
			}

		});
		column.setWidth(95);
		configs.add(column);

		column = new ColumnConfig();

		final ListStore<TimeslotMD> store = new ListStore<TimeslotMD>();
		List<TimeslotMD> slots = new ArrayList<TimeslotMD>();
		slots.add(new TimeslotMD(new Date(2011 - 1900, 4, 2, 8, 00), new Date(2011 - 1900, 4, 2,
				20, 00)));
		slots.add(new TimeslotMD(new Date(2011 - 1900, 4, 4, 8, 00), new Date(2011 - 1900, 4, 4,
				20, 00)));
		slots.add(new TimeslotMD(new Date(2011 - 1900, 4, 6, 8, 00), new Date(2011 - 1900, 4, 6,
				20, 00)));
		store.add(slots);

		ColumnModel cm = new ColumnModel(configs);

		ContentPanel cp = new ContentPanel();

		cp.setHeading("Zeitslot auswahl");
		cp.setFrame(true);
		cp.setSize(320, 200);
		cp.setLayout(new FitLayout());

		final RowEditor<TimeslotMD> re = new RowEditor<TimeslotMD>();
		final Grid<TimeslotMD> grid = new Grid<TimeslotMD>(store, cm);
		// grid.setAutoExpandColumn("datum");
		grid.setBorders(true);

		grid.addPlugin(re);
		grid.getAriaSupport().setLabelledBy(cp.getHeader().getId() + "-label");
		cp.add(grid);

		ToolBar toolBar = new ToolBar();
		Button add = new Button("Slot hinzufuegen");
		add.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				TimeslotMD plant = new TimeslotMD(new DateWrapper().clearTime().asDate(),
						new DateWrapper().clearTime().asDate());

				re.stopEditing(false);
				store.insert(plant, 0);
				re.startEditing(store.indexOf(plant), true);

			}

		});
		toolBar.add(add);
		cp.setTopComponent(toolBar);
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		cp.setTopComponent(toolBar);
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		simple.addButton(new Button("Abbrechen", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				abbrechen();
			}
		}));
		simple.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				store.rejectChanges();
			}
		}));
		simple.addButton(new Button("Save", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				store.commitChanges();

				if (isFormvalide()) {
					Set<TimeslotAdminDTO> list = (Set<TimeslotAdminDTO>) TimeslotMD
							.convertSlots(store.getModels());
					poll = new PollDTO(owner.getValue(), titel.getValue(), beschreibung.getValue(),
							email.getValue(), ort.getValue(), Short.parseShort(dauer.getValue()), list);
					chronixService.createPoll(poll, new AsyncCallback<PollDTO>() {

						@Override
						public void onSuccess(PollDTO result) {
							System.out.println("OnsuccessID" + result.getId());
							pollCreateSucsess(result);
						}

						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}
					});

				}
			}
		}));

		simple.add(cp);

		vp.add(simple);

	}
private void abbrechen(){
	Chronix.clearPanel(this);
	Chronix.insertStartpage();
}
	void pollCreateSucsess(PollDTO result) {
		Chronix.clearPanel(this);
		Chronix.insertLinkpage(result);
	}

	public boolean isFormvalide() {
		if (!simple.isValid()) {
			Window.alert("Bitte vervollstaendigen Sie das Formular und schicken es erneut ab");
			return false;
		} else {
			return true;
		}
	}

}
